package com.qqtech.qquan.order.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.admin.context.AdminPage;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.qquan.homemaking.service.HomemakingOrderService;
import com.qqtech.qquan.mall.enums.MallSupplierStatusDictEnum;
import com.qqtech.qquan.mall.model.MallSupplier;
import com.qqtech.qquan.mall.model.MallSupplierQuery;
import com.qqtech.qquan.mall.service.MallShopService;
import com.qqtech.qquan.mall.service.MallSupplierService;
import com.qqtech.qquan.order.enums.OrderDeliveryTypeDictEnum;
import com.qqtech.qquan.order.model.OrderBase;
import com.qqtech.qquan.order.model.OrderDelivery;
import com.qqtech.qquan.order.model.OrderItem;
import com.qqtech.qquan.order.model.OrderSplit;
import com.qqtech.qquan.order.model.OrderSplitQuery;
import com.qqtech.qquan.order.model.OrderSplitVo;
import com.qqtech.qquan.order.service.OrderBaseService;
import com.qqtech.qquan.order.service.OrderDeliveryService;
import com.qqtech.qquan.order.service.OrderItemService;
import com.qqtech.qquan.order.service.OrderSplitService;
import com.qqtech.qquan.order.service.OrderSysDictService;
import com.qqtech.qquan.sys.controller.BaseAdminController;
import com.qqtech.qquan.sys.enums.SysConst;
import com.qqtech.qquan.sys.model.SysParam;
import com.qqtech.qquan.sys.service.SysParamService;
import com.qqtech.qquan.user.model.UserBase;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.qquan.util.ExcelUtil;


@Controller
@RequestMapping(value = "/order/split")
public class OrderSplitController extends BaseAdminController {
	@Resource
	private OrderBaseService orderBaseService;
	@Resource
	private OrderSplitService orderSplitService;
	@Resource
	private OrderDeliveryService orderDeliveryService;

	@Resource
	private OrderItemService orderItemService;

	@Resource
	private UserBaseService userBaseService;

	@Resource
	private HomemakingOrderService homemakingOrderService;
	
	@Resource
	private MallShopService mallShopService;
	@Resource
	private OrderSysDictService orderSysDictService;
	@Resource
	private MallSupplierService mallSupplierService;
	@Resource
	private SysParamService sysParamService;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		MallSupplierQuery supplierQuery = new MallSupplierQuery();
		supplierQuery.setStatus(MallSupplierStatusDictEnum.NORMAL.getCode());
		supplierQuery.setIsShow(YesNoEnum.YES.getCode());
		Pageable pageKit = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.ASC, "id"));
		List<MallSupplier> mallSupplierList = mallSupplierService.queryList(supplierQuery, pageKit);
		model.addAttribute("mallSupplierList", mallSupplierList);
		return "/order/ordersplit-list";
	}
	
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list(OrderSplitQuery query, HttpServletRequest request, HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		String rows = (String) request.getParameter("rows"); // 每页条数
		query.setSize(Integer.valueOf(rows));
		Pageable pageKit = new PageKit(query.getPage(), query.getSize(), new PageOrder(Direction.DESC, "newAt"));
		Page<OrderSplitVo> page = orderSplitService.queryPageList(query, pageKit);
		List<OrderSplitVo> orderList = page.getContent();
		if(orderList!=null && orderList.size()>0){
			for(OrderSplitVo order : orderList){
				if (order.getSellerId() != null && order.getSellerId().intValue() != 0) {
					UserBase seller = userBaseService.getById(order.getSellerId());
					if(seller!=null){
						order.setSellerName(seller.getNick());
					}
				}
			}
		}
		adminPage.setRows(orderList);
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}

	@RequestMapping(value = "/detail")
	public String detail(OrderSplitQuery query, Model model) {
		OrderSplit order = orderSplitService.getById(query.getId());
		if (order != null) {
			OrderBase orderBase = orderBaseService.getByOrderNo(order.getOrderNo());
			if(orderBase!=null){
				List<OrderItem> itemList = orderItemService.findByOrderNo(order.getOrderNo());
				int deliveryType = OrderDeliveryTypeDictEnum.SELLERSEND.getCode();
				if (order.getSellerId() != null && order.getSellerId().intValue() != 0) {
					UserBase seller = userBaseService.getById(order.getSellerId());
					if(seller!=null){
						model.addAttribute("sellerName", seller.getNick());
					}
				}
				UserBase buyer = userBaseService.getById(orderBase.getBuyerId());
				OrderDelivery delivery = orderDeliveryService.getByOrderNoAndType(order.getOrderNo(),deliveryType);
				model.addAttribute("order", order);
				model.addAttribute("itemList", itemList);
				model.addAttribute("delivery", delivery);
				if(buyer!=null){
					model.addAttribute("buyerName", buyer.getNick());
				}
			}
		}
		return "/order/ordersplit-detail";
	}
	
	@RequestMapping(value = "/export2Excel")
	@ResponseBody
	public Result export2Excel(OrderSplitQuery query, HttpServletRequest request, HttpServletResponse response) {
		Result ret = new Result();
		Pageable pageKit = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.DESC, "newAt"));
		int count = orderSplitService.queryCount(query);
		SysParam sysParam = sysParamService.getByKey(SysConst.PARAM_SYS_EXPORT_TOEXCEL_MAXROWS);
		if (sysParam != null && StringUtil.isNotBlank(sysParam.getValue())) {
			int maxExportRows = Integer.valueOf(sysParam.getValue());
			if(count > maxExportRows){
				ret.addErr("导出数量不能超过"+maxExportRows+"行!");
				return ret;
			}
		}
		List<OrderSplitVo> orderList =  orderSplitService.queryList(query, pageKit);//不分页
		if(orderList!=null && orderList.size()>0){
			for(OrderSplitVo order : orderList){
				if (order.getSellerId() != null && order.getSellerId().intValue() != 0) {
					UserBase seller = userBaseService.getById(order.getSellerId());
					if(seller!=null){
						order.setSellerName(seller.getNick());
					}
				}
			}
		}
		List<Map<String,Object>> list=createExcelRecord(orderList);
    	String columnNames[]={"订单号","供应商","卖方","实际分账金额(元)","原本分账金额","分账比例","分账状态","下单时间"};//列名
        String keys[]   =    {"orderNo","supplierName","sellerName","value","originalValue","rate","status","strNewAt"};//map中的key
        String fileName="订单-分账单";
        ExcelUtil.ExcelSingleOutputStream(list,keys,columnNames,fileName,request,response);
        return ret;
	}
	
    private List<Map<String, Object>> createExcelRecord(List<OrderSplitVo> orderList) {
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sheetName", "分账单");
        listmap.add(map);
        OrderSplitVo order=null;
        for (int j = 0; j < orderList.size(); j++) {
        	order=orderList.get(j);
            Map<String, Object> mapValue = new HashMap<String, Object>();
            mapValue.put("orderNo", order.getOrderNo());
            mapValue.put("supplierId", order.getSupplierId());
            mapValue.put("supplierName", order.getSupplierName());
            mapValue.put("sellerId", order.getSellerId());
            mapValue.put("sellerName", order.getSellerName());
            mapValue.put("value", order.getValue());
            mapValue.put("originalValue", order.getOriginalValue());
            mapValue.put("rate", order.getRate());
            mapValue.put("status", order.getStatus()==1? "已分账" : "未分账");
            mapValue.put("strNewAt", order.getStrNewAt());
            listmap.add(mapValue);
        }
        return listmap;
    }
    
}
